<template>
  <div id="capture">
    <div class="main">
      <div class="main-left">
        <h2>待抓取项目</h2>
        <div v-if="atTableData.length != 0">
          <span class="count">( 已选择{{ count }}个项目 )</span>
          <!-- 表格 -->
          <table>
            <!-- 表头 -->
            <thead class="ant-table-thead">
              <tr>
                <!-- 项目标题 -->
                <th
                  class="ant-table-row-cell-break-word resize-table-th th-title"
                >
                  <div class="title">
                    <div class="orderNumber">
                      <!-- 全选 -->
                      <a-checkbox
                        :checked="pageCounts[current].checkAll"
                        @change="onCheckAllChange"
                      ></a-checkbox>
                    </div>
                    <svg class="icon" aria-hidden="true">
                      <use xlink:href="#icon-faguangdengpao"></use>
                    </svg>
                    <span>项目标题</span>
                  </div>
                </th>
                <!-- 评分 -->
                <th
                  class="ant-table-row-cell-break-word resize-table-th th-grade"
                >
                  <div class="grade">
                    <svg class="icon" aria-hidden="true">
                      <use xlink:href="#icon-pingfen"></use>
                    </svg>
                    教师评分
                  </div>
                </th>
              </tr>
            </thead>

            <!-- 表格主体 -->
            <tbody class="ant-table-tbody table-body">
              <tr
                class="ant-table-row ant-table-row-level-0"
                v-for="(item, index) in atTableData"
                :key="index"
                @mouseenter="item.showCheck = true"
                @mouseleave="item.showCheck = false"
              >
                <template v-if="item.isEmpty">
                  <td class="ant-table-row-cell-break-word"></td>
                  <td class="ant-table-row-cell-break-word"></td>
                </template>
                <template v-else>
                  <!-- 项目标题 -->
                  <td class="ant-table-row-cell-break-word td-title">
                    <div class="title">
                      <div
                        class="orderNumber"
                        v-if="item.checked || item.showCheck"
                      >
                        <a-checkbox
                          :checked="item.checked"
                          @change="
                            onCheck((item.checked = $event.target.checked))
                          "
                        >
                        </a-checkbox>
                      </div>
                      <div class="orderNumber" v-else>
                        {{ index + 1 }}
                      </div>
                      <div class="titleName">
                        {{ item._title }}
                      </div>
                      <!-- 移入显示全部 -->
                      <div class="allTitleName">
                        {{ item.title }}
                      </div>
                    </div>
                  </td>
                  <!-- 评分 -->
                  <td class="ant-table-row-cell-break-word">
                    <div>
                      <a-rate
                        :default-value="item.score / 2"
                        :disabled="true"
                        :allowHalf="true"
                      >
                      </a-rate>
                    </div>
                  </td>
                </template>
              </tr>
            </tbody>
          </table>
          <!-- 分页 -->
          <div class="page">
            <ul v-if="pageCounts.length > 1">
              <li
                v-for="(page, index) in pageCounts"
                :key="index"
                @click="goto(index)"
              >
                <span :class="{ active: current == index }">{{
                  page.count
                }}</span>
              </li>
            </ul>
          </div>
          <div class="button-box">
            <a-button @click="captureProj">抓取项目</a-button>
          </div>
        </div>
        <div class="noCentent-box" v-else>
          <img src="../../assets/img/capture/noCentent.png" />
          <span>请先提取项目</span>
        </div>
      </div>

      <!-- 项目来源 -->
      <div class="main-right">
        <!-- 关闭图标 -->
        <i class="share" @click="close">
          <a-icon type="close" />
        </i>
        <h2>
          抓取来源
          <div class="open" tabindex="1" @click="openMenu">
            <svg class="icon up" aria-hidden="true">
              <use xlink:href="#icon-arrow-up"></use>
            </svg>
            <svg class="icon down" aria-hidden="true">
              <use xlink:href="#icon-arrow-down"></use>
            </svg>
          </div>
          <div class="close" tabindex="2" @click="closeMenu">
            <svg class="icon up" aria-hidden="true">
              <use xlink:href="#icon-arrow-down"></use>
            </svg>
            <svg class="icon down" aria-hidden="true">
              <use xlink:href="#icon-arrow-up"></use>
            </svg>
          </div>
        </h2>
        <span class="count">（ 已选择{{ countRight }}项 ）</span>

        <div class="menu-box">
          <a-menu
            mode="inline"
            :selectable="false"
            style="width: 256px"
            :open-keys="openKeys"
            @openChange="onOpenChange"
          >
            <a-sub-menu v-for="(item, index) in captureData" :key="index">
              <span slot="title" class="menu-title">
                <!-- 全选 -->
                <a-checkbox
                  :indeterminate="item.indeterminate"
                  :checked="item.checkAll"
                  @click.stop=""
                  @change="onCapCheckAllChange(index)"
                  class="check-box"
                >
                </a-checkbox>
                <span>{{ item.ClassName }}</span>
                <!-- 虚线 -->
                <i class="dottedLine"></i>
                <span>{{ item.teacher }}</span>
              </span>
              <a-menu-item
                v-for="(item1, index1) in item.HomeworkList"
                :key="index1"
                @click="onCapChecked(index, index1)"
                v-if="item.HomeworkList.length > 0"
              >
                <a-checkbox
                  :checked="item1.checked"
                  class="check-box"
                  @change="
                    onCapCheck((item1.checked = $event.target.checked), index)
                  "
                >
                </a-checkbox>
                {{ index1 + 1 + " " + item1.Name }}
              </a-menu-item>
            </a-sub-menu>
          </a-menu>
        </div>
        <!-- 提取按钮 -->
        <div class="button-box">
          <button @click="extract">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-zuojiantou"></use>
            </svg>
            提取
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
const tableCountMax = 50; // 表格单页最多显示数量

export default {
    name: "capture",
    data() {
        return {
            // 表格所有数据
            tableData: [{ isEmpty: true }],
            // 表格当前显示的数据
            atTableData: [],
            //抓取来源部分的数据
            captureData: [],
            // 分页多选控制数组
            pageCounts: [{ count: 0, checkAll: false, indeterminate: false, }],
            current: 0, //当前页码 (0为第一页)
            // 当前展开的下拉菜单
            openKeys: [],
            reminder: '' ,// 提示信息
            // 额外属性
            extraAttribute:null,
        };
    },
    created() {
        // 获取项目来源部分的数据
        this.getCaptureData()
        this.initUser();
        this.refreshTable();
        this.pageCount()
    },
    mounted() {
        this.extraAttribute=this.$store.state.attribute.allAttribute
    },
    computed: {
        // 已选择项目数量(抓取)
        count: function () {
            var count = 0;
            this.tableData.forEach((item, index) => {
                if (item.checked == true) {
                    count++;
                }
            });
            return count;
        },
        // 已选择的项目数(提取)
        countRight: function () {
            var count = 0;
            this.captureData.forEach((item, index) => {
                if (item.checked == true) {
                    count += item.HomeworkList.length;
                } else {
                    item.HomeworkList.forEach((item, index) => {
                        if (item.checked == true) {
                            count++;
                        }
                    });
                }
            });
            return count;
        },
        // 过滤表格数据
        table() {
            var tab = this.atTableData.filter(function (value) {
                return value.isEmpty !== true;
            });
            return tab;
        },
        ...mapState({
            // 管理员数据
            user: (state) => state.user.user,
            // 额外属性
            // extraAttribute:(state) => state.attribute.allAttribute,
        }),
    },
    methods: {
        ...mapActions({ initUser: 'initUser' }),
        // 刷新表格数据
        refreshTable() {
            var tab = this.tableData.filter(function (value) {
                return value.isEmpty !== true;
            });
            // 截取数组
            this.atTableData = tab.slice(0 + (this.current * tableCountMax), tableCountMax + (this.current * tableCountMax));
            return tab
        },
        // 页数
        pageCount() {
            var page = [];
            // 总页数
            let allpage = Math.ceil((this.tableData.length / tableCountMax));
            while (allpage) {
                page.unshift({ count: allpage--, checkAll: false, indeterminate: false, });
            }
            this.pageCounts = page;
        },
        // 关闭项目详情弹窗
        close() {
            this.$emit("closeCapture");
        },
        // 表格单选
        onCheck(val) {
            var a = 0;
            this.table.forEach((item, index) => {
                if (item.checked == true) {
                    a++;
                }
            });
            // 控制选择时样式变换
            if (a == 0) {
                this.pageCounts[this.current].indeterminate = false;
                this.pageCounts[this.current].checkAll = false;
            } else if (a == this.table.length) {
                this.pageCounts[this.current].indeterminate = false;
                this.pageCounts[this.current].checkAll = true;
            } else {
                this.pageCounts[this.current].indeterminate = true;
            }
        },
        // 表格全选
        onCheckAllChange() {
            this.pageCounts[this.current].checkAll = !this.pageCounts[this.current].checkAll;
            this.checkAll = !this.checkAll
            this.table.forEach(item => {
                item.checked = this.checkAll;
            });

        },
        // 页码跳转
        goto(index) {
            this.current = index;
            this.refreshTable();
        },
        // 抓取项目按钮
        captureProj() {
            if (this.count < 1) {
                this.$message.warning('您当前还没有选择项目')
            } else {
                this.$confirm('是否抓取已选择的' + this.count + '个项目', async () => {
                    let newDatas = [];
                    this.tableData.forEach((item, index, arr) => {
                        if (item.checked == true) {
                            item.checked = false;
                            newDatas.push(item);
                            delete arr[index];
                        }
                    });
                    
                    // 将数据存入数据库
                   let {data : newData}= await this.$api.projectMessage.batchAdd(newDatas);
                   newData.forEach(item=>{
                    item.attrs=[]
    
                        this.extraAttribute.forEach(item2=>{
                            item.attrs.push({
                            id: item2.id,
                            name: item2.value,
                            value: "",
                        });
                        })
                        console.log(this.extraAttribute)
                
                    item.files=[]
                    item.notes=[]
                   })
                    // 清除数组空元素
                    this.$store.commit('setNewTableData', newData)
                    this.tableData = this.tableData.filter(function (value) {
                        return value;
                    });
                    if (this.tableData.length === 0) {
                        this.tableData = [{ isEmpty: true }];
                    }
                    this.close();
                    this.$emit("openLoadding");
                })
            }
        },
        // 获取项目来源部分的数据
        async getCaptureData() {
            let res = await this.$api.captureData.getClassMessage().then(res => res.data);
            res.forEach((item) => {
                const newData = {
                    ClassName: '',
                    teacher: '(无教师)',
                    PK_ClassGuid: '',
                    indeterminate: false,
                    checkAll: false,
                    HomeworkList: []
                };
                // 去除无项目的班级
                if (item.HomeworkList.length > 0) {
                    newData.ClassName = item.ClassName;
                    newData.PK_ClassGuid = item.PK_ClassGuid;
                    newData.teacher = item.TeacherName;

          item.HomeworkList.forEach((item, index) => {
            const newHomeworkList = {
              Name: "",
              CreateTime: "",
              FK_ClassGuid: "",
              FK_GroupSchemeGuid: null,
              PK_HomeworkGuid: "",
              Question: null,
              SubmitType: "",
              checked: false,
              showCheck: false,
            };

            if (item.Name) newHomeworkList.Name = item.Name;
            if (item.CreateTime) newHomeworkList.CreateTime = item.CreateTime;
            if (item.FK_ClassGuid)
              newHomeworkList.FK_ClassGuid = item.FK_ClassGuid;
            if (item.FK_GroupSchemeGuid)
              newHomeworkList.FK_GroupSchemeGuid = item.FK_GroupSchemeGuid;
            if (item.PK_HomeworkGuid)
              newHomeworkList.PK_HomeworkGuid = item.PK_HomeworkGuid;
            if (item.Question) newHomeworkList.Question = item.Question;
            if (item.SubmitType) newHomeworkList.SubmitType = item.SubmitType;

            newData.HomeworkList.push(newHomeworkList);
          });
          this.captureData.push(newData);
        }
      });
    },
    // 抓取来源-单选(点击字体设置选中)
    onCapChecked(val, val1) {
      this.captureData.forEach((item, index) => {
        if (val === index) {
          var a = 0;
          item.HomeworkList.forEach((item, index) => {
            if (val1 === index) {
              item.checked = !item.checked;
            }
            if (item.checked == true) {
              a++;
            }
          });
          // 控制选择时样式变换
          if (a == 0) {
            item.indeterminate = false;
            item.checkAll = false;
          } else if (a == item.HomeworkList.length) {
            item.indeterminate = false;
            item.checkAll = true;
          } else {
            item.indeterminate = true;
          }
        }
      });
    },
    // 抓取来源-单选
    onCapCheck(val, index1) {
      // this.captureData.forEach((item, index) => {
      //     if (index1 === index) {
      //         var a = 0;
      //         item.HomeworkList.forEach((item, index) => {
      //             if (item.checked == true) {
      //                 a++;
      //             }
      //         });
      //     }
      // });
    },
    // 抓取来源-全选
    onCapCheckAllChange(index1) {
      this.captureData.forEach((item, index) => {
        if (index === index1) {
          item.checkAll = !item.checkAll;
          item.HomeworkList.forEach((item, index) => {
            item.checked = !item.checked;
          });
        }
      });
    },
    // 提取按钮
    async extract() {
      if (this.countRight < 1) {
        this.$message.warning("您当前还没有选择项目");
      } else {
        this.$confirm(
          "是否从已选择的" + this.countRight + "个作业中提取项目",
          () => {
            // 已选择的项目列表
            let checkedData = [];
            this.captureData.forEach((item) => {
              item.HomeworkList.forEach((item) => {
                if (item.checked == true) {
                  checkedData.push(item);
                }
              });
            });

            let have = false;
            // 获取布置作业下的所有学生作业
            new Promise((resolve) => {
              checkedData.forEach(async (item, index) => {
                let FK_HomeworkGuid = item.PK_HomeworkGuid;
                let SubmitType = item.SubmitType;
                let res = await this.$api.captureData
                  .getHomeworkAll(FK_HomeworkGuid, SubmitType)
                  .then((res) => res.data);

                if (res.length > 0) {
                  res.forEach((item) => {
                    const newData = {
                      adminId: this.user.id,
                      title: "(项目标题)",
                      type: "未分类项目",
                      tags: "",
                      score: 0,
                      introduction: "",
                      contact: "(联系电话)",
                      members: "",
                      showCheck: false,
                      checked: false,
                    };
                    newData.score = item.Score;
                    newData.title = item.Title;
                    newData.contact = item.memberList[0].phone || null;

                    item.memberList.forEach((item1, index) => {
                      if ((item.memberList.length = index + 1)) {
                        newData.members = item1.userName;
                      } else {
                        newData.members += item1.userName + "、";
                      }
                    });
                    this.tableData.push(newData);
                  });
                  // 重新刷新表格
                  this.pageCount();
                  this.tableData = this.refreshTable();
                  have = true;
                  resolve(have);
                } else if (index == checkedData.length - 1 && !have) {
                  resolve(have);
                }
              });
            }).then((result) => {
              if (!result) {
                this.$message.warning("查询到0项");
              }
            });
          }
        );
      }
    },
    // 单个下拉菜单展开/关闭
    onOpenChange(openKeys) {
      this.openKeys = openKeys;
    },
    // 展开所有下拉菜单
    openMenu() {
      let openKeys = [];
      for (let i = 0; i < this.captureData.length; i++) {
        openKeys.push(i);
      }
      this.openKeys = openKeys;
    },
    // 关闭所有展开的下拉菜单
    closeMenu() {
      this.openKeys = [];
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./capture.scss";
</style>
